//
//  DDcacheManager.m
//  hnGovernment
//
//  Created by 张辉男 on 17/3/7.
//  Copyright © 2017年 安仔. All rights reserved.
//

#import "DDcacheManager.h"
#import "MJExtension.h"
#import "ZWUserModel.h"

#define KtokenKey @"ktokenKey"
@interface DDcacheManager()
@property (nonatomic,strong) NSLock *lock;
@end

@implementation DDcacheManager

+ (instancetype)shareInstance {
    static dispatch_once_t onceToken;
    static DDcacheManager *manager;
    dispatch_once(&onceToken    , ^{
        manager = [[DDcacheManager alloc]init];
        manager.lock = [[NSLock alloc]init];
    });
    return manager;
}

- (void)cacheUserToken:(NSString *)token {
    [self.lock lock];
    [[NSUserDefaults standardUserDefaults]setObject:token forKey:KtokenKey];
    [self.lock unlock];
}

- (NSString *)userToken {
    return [[NSUserDefaults standardUserDefaults]objectForKey:KtokenKey];
}

- (void)cacheUserInfoWithModel:(ZWUserModel *)userModel {
    NSString *path = [DDcacheManager cachePath];
    [self.lock lock];
    [NSKeyedArchiver archiveRootObject:userModel toFile:path];
    [self.lock unlock];
}

- (void)cacheUserInfo:(NSDictionary *)userInfo {
    ZWUserModel *user = [ZWUserModel objectWithKeyValues:userInfo];
    NSString *path = [DDcacheManager cachePath];
    [self.lock lock];
    [NSKeyedArchiver archiveRootObject:user toFile:path];
    [self.lock unlock];
}

- (void)clearUserInfo {
    [self.lock lock];
    [[NSFileManager defaultManager]removeItemAtPath:[DDcacheManager cachePath] error:nil];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:KtokenKey];
    [self.lock unlock];
}

- (ZWUserModel *)getUserModel {
    return (ZWUserModel *)[NSKeyedUnarchiver unarchiveObjectWithFile:[DDcacheManager cachePath]];
}

+ (NSString *)cachePath {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"user.archiver"];
}
@end
